import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/ui/src/slide_panel.dart';
import 'package:flutter_smart_heating/ui/ui.dart';

class FilterData {
  Map<String, dynamic> params = {};
  bool state = false;
  FilterData({
    this.params = const {},
    this.state = false,
  });
}

class FilterView extends StatefulWidget {
  const FilterView({
    super.key,
    required this.body,
    required this.filter,
    this.onChange,
    this.onCreated,
  });
  final Widget body;
  final String filter;

  final Function(FilterData filter)? onChange;
  final Function(
          BuildContext context, PanelController controller, FilterData filter)?
      onCreated;

  @override
  State<FilterView> createState() => _FilterViewState();
}

class _FilterViewState extends State<FilterView> {
  ValueNotifier loading = ValueNotifier<bool>(true);
  List<dynamic> filterConfig = [];
  PanelController controller = PanelController();
  FilterData filterData = FilterData();
  @override
  void initState() {
    fetchFilterConfig();
    super.initState();
  }

  Future fetchFilterConfig() async {
    var res = await Http.instance.post(
      '/api/information/filter/index',
      data: filterParams,
    );
    if (res.code == 1) {
      filterConfig = res.data;
    }
    setState(() {});
    if (context.mounted) {
      filterData.state = hasFilter;
      filterData.params = filterParams;
      widget.onCreated?.call(context, controller, filterData);
    }
  }

  /// 确定搜索
  confirmSearch() {
    filterData.state = hasFilter;
    filterData.params = filterParams;
    controller.close();
    widget.onChange?.call(filterData);
  }

  /// 取得筛选项
  Map<String, dynamic> get filterParams {
    Map<String, dynamic> params = {
      'filter': widget.filter,
    };
    for (var item in filter) {
      if (item['value'] != null) {
        params[item['field']] = item['value'];
      }
    }
    return params;
  }

  /// 筛选列表
  List<dynamic> get filter =>
      filterConfig.where((element) => element['enable']).toList();

  /// 是否有选中了筛选项
  bool get hasFilter =>
      filter.where((element) => element['value'] != null).isNotEmpty;

  @override
  Widget build(BuildContext context) {
    return SlidingUpPanel(
      controller: controller,
      slideDirection: SlideDirection.DOWN,
      minHeight: 0,
      maxHeight:
          (hasFilter ? 85 : UiTheme.toolbarSpacing + 2) + filter.length * 83,
      backdropEnabled: true,
      color: UiTheme(context).match(
        dark: Theme.of(context).scaffoldBackgroundColor,
        light: Colors.white,
      ),
      boxShadow: const [],
      padding: const EdgeInsets.symmetric(horizontal: UiTheme.spacingX),
      onPanelOpened: () async {
        if (filter.isEmpty) {
          await fetchFilterConfig();
        }
      },
      panel: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: UiTheme.toolbarSpacing),
          for (var options in filter)
            Container(
              margin: const EdgeInsets.only(bottom: UiTheme.spacingXX),
              height: 65,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(options['label']),
                  Expanded(
                    child: ListView.separated(
                      scrollDirection: Axis.horizontal,
                      separatorBuilder: (content, index) =>
                          const SizedBox(width: 10),
                      itemBuilder: (context, index) {
                        var item = options['items'][index];
                        return filterItemView(
                          label: item['label'] ?? '',
                          value: item['value'] ?? '',
                          isActived: item['value'] == options['value'],
                          onTap: (val, isActived) async {
                            options['value'] = isActived ? null : val;
                            loading.value = true;
                            if (options['update'] != null) {
                              for (var f in filter) {
                                if (f['field'] == options['update']) {
                                  f['value'] = null;
                                  f['items'].clear();
                                }
                              }
                              fetchFilterConfig();
                            }
                            confirmSearch();
                          },
                        );
                      },
                      itemCount: options['items'].length,
                    ),
                  )
                ],
              ),
            ),
          if (hasFilter)
            Divider(
              height: 0,
              thickness: UiTheme(context).match(light: 0.5, dark: 0.2),
            ),
          if (hasFilter)
            Container(
              margin: const EdgeInsets.only(top: UiTheme.spacingXX),
              child: Row(
                children: [
                  Expanded(
                    child: UiTap(
                      onTap: () {
                        if (hasFilter) {
                          bool needUpdateConfig = true;
                          for (var element in filter) {
                            if (element['update'] == true &&
                                element['value'] != null) {
                              needUpdateConfig = true;
                            }
                            element['value'] = null;
                          }
                          loading.value = true;
                          confirmSearch();
                          if (needUpdateConfig) {
                            fetchFilterConfig();
                          }
                        }
                      },
                      child: UiPanel(
                        width: double.infinity,
                        height: 38,
                        backgroundColor:
                            UiTheme.of(context).match(light: Colors.grey[100]),
                        border: Border.all(color: Colors.grey, width: 0.2),
                        borderRadius: BorderRadius.circular(5),
                        child: Center(
                          child: Text(
                            '重置',
                            style: TextStyle(
                              color: hasFilter
                                  ? null
                                  : Colors.grey.withOpacity(0.5),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            )
        ],
      ),
      body: widget.body,
    );
  }

  Widget filterItemView({
    String? label,
    dynamic value,
    bool isActived = false,
    Function(dynamic, bool)? onTap,
  }) {
    return UiTap(
      onTap: () {
        onTap?.call(value, isActived);
      },
      child: Stack(
        children: [
          Container(
            width: 90,
            margin: const EdgeInsets.only(top: 10),
            decoration: BoxDecoration(
              color: isActived
                  ? UiTheme.primary
                  : UiTheme.of(context).panelBackground,
              borderRadius: BorderRadius.circular(5),
              border: Border.all(color: Colors.grey, width: 0.2),
            ),
            alignment: Alignment.center,
            child: Text(
              label ?? '',
              textAlign: TextAlign.center,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: UiTheme(context).matchColor(
                    isActived ? Colors.white : Colors.black87, Colors.white70),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
